import NSys from '@/n-sys.js';
import store from '@/utils/store'
import auth from '@/utils/auth'
const {Vue,base,conf,t, msg, navProg,  VueRouter  } = NSys;


import PAGES from '@/router/pages.js';

Vue.use(VueRouter)


const router = new VueRouter({
	mode: 'hash',
	scrollBehavior: () => ({ y: 0 }),
	routes:  [
		{
			path: '/', 
			redirect: '/pages/marketing',
		},
		
		...PAGES,
		{
			path: '/login',
			component: () => import('@/views/login'),
			meta: { title: "登录", cache:0 },
		},
		{
			path: '/404',
			component: () => import('@/views/404'),
			meta: { title: "404", cache:0 },
		},
	]
})

export const getCacheKey = r => {
	const {meta,path,query} = r;
	if(!meta) return path;
	
	const {cache, cacheKey,queryCacheKey} = meta;
	if(!cache) return false;
	if(cacheKey) return base.isType(cacheKey) === 'function' ? cacheKey(r) : cacheKey;
	if(queryCacheKey) return query[queryCacheKey] || path;
	return path;
}


export const getTitle = r => {
	if(!r.meta) return ''
	if(r.query && r.meta.queryTitleKey && r.query[r.meta.queryTitleKey]) return r.query[r.meta.queryTitleKey]
	return   base.isType(r.meta.navTitle) === 'function' ? r.meta.navTitle(r) : r.meta.navTitle || r.meta.title;
};



router.beforeEach(async (to, from, next) => {
	navProg.start()
	document.title = t(getTitle(to) || '');
	
	if(to.query._shareId) store.set('shareId',to.query._shareId)
	
	const {userInfo} = store;
	if(to.path === '/pages/me' && (!userInfo || userInfo.type !== 1)) return next('/pages/home');
	
	
	if(['/pages/live-analysis/keyword','/pages/live-analysis/data'].includes(to.path)  ) {
		if( userInfo && userInfo.type === 2) return next('/pages/order');
		if(!auth.isLogin()) return next(`/pages/login?redirect=${ to.fullPath }`);
	}
	
	if( ['/login', '/404'].includes(to.path) ) return next()
	
	 
	next();
})

// 路由跳转后执行
router.afterEach(() =>navProg.end());

export default router
 


